import { getUserInfo, login } from '@/api/user'
import { getToken, removeToken, setTime, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
    setTime(Date.now())
  },
  removeToken(state) {
    state.token = ''
    removeToken()
  },
  setUserInfo(state, data) {
    state.userInfo = data
  },
  removeUserInfo() {
    state.userInfo = {}
  }
}
const actions = {
  async login({ commit }, payload) {
    const data = await login(payload)
    // console.log(data)
    commit('setToken', data)
  },
  async getUserInfo({ commit }) {
    const data = await getUserInfo()
    // console.log(data)
    commit('setUserInfo', data)
  },
  logout({ commit }) {
    commit('removeToken')
    commit('removeUserInfo')
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
